<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <script src="/js/jquery-1.12.1.min.js"></script>
    <script src="/editor/editormd.min.js"></script>
    <link rel="stylesheet" href="/editor/css/style.css" />
    <link rel="stylesheet" href="/editor/css/editormd.css" />
    <script>
        tinymce.init({
            selector: '#tinymce_demo', //容器，可使用css选择器
            language:'zh_CN', //调用放在langs文件夹内的语言包
            toolbar: true, //工具栏
            menubar: true, //菜单栏
            branding:false, //右下角技术支持
            inline: false, //开启内联模式
            elementpath: false,
            min_height:400, //最小高度
            height: 800,  //高度
            skin: 'oxide',
            toolbar_sticky:true,
            visualchars_default_state:true, //显示不可见字符
            image_caption: true,
            paste_data_images: true,
            relative_urls : false,
            // remove_script_host : false,
            removed_menuitems: 'newdocument',  //清除“文件”菜单
            plugins: "lists,hr, advlist,anchor,autolink,autoresize,charmap,code,codesample,emoticons,fullscreen,image,media,insertdatetime,link,pagebreak,paste,preview,print,searchreplace,table,textcolor,toc,visualchars,wordcount", //依赖lists插件
            toolbar: 'bullist numlist anchor charmap advlist emoticons fullscreen hr code table image insertdatetime link media pagebreak paste preview print searchreplace textcolor wordcount',
            //选中时出现的快捷工具，与插件有依赖关系
            images_upload_url:'a.php' /*后图片上传接口*/ /*返回值为json类型 {'location':'uploads/jpg'}*/
            // setup: function(editor){
            //     editor.on('change',function(){ editor.save(); });
            // }
        });
    </script>
    <style>
        body {
            background-color: #ffffff;
        }
        #treeView {
            width: 600px;
            margin: 20px auto 0;
            border: 1px solid #f2f2f2;
        }
        .treeNode {
            height: 32px;
            border: 1px solid #fff;
            border-width: 1px 0;
            cursor: pointer;
            font-size: 0;
        }
        .treeNode:hover {
            background: #f4f9fd;
            border-color: #e5f0fb;
        }
        .treeNode-cur,
        .treeNode-cur:hover {
            background: #e5f0fb;
            border-color: #BBD4EF #fff;
        }
        .icon {
            display: inline-block;
            background: url(icon.png) no-repeat;
            vertical-align: middle;
        }
        .icon-minus {
            width: 15px;
            height: 15px;
            margin: 0 4px;
            background-position: -30px -22px;
        }
        .icon-add {
            width: 15px;
            height: 15px;
            margin: 0 4px;
            background-position: -30px 0;
        }
        .icon-file {
            width: 22px;
            height: 18px;
            margin-right: 5px;
            background-position: 0 -22px;
        }
        .title {
            position: relative;
            top: 6px;
            font-size: 14px;
        }

        .treeNode-empty .icon-minus {
            background-position: -999px -999px;
        }
        .treeNode-empty .icon-add {
            background-position: -999px -999px;
        }

        #treeView ul.none {
            display: none;
        }
    </style>
</head>
<body>
<div>

    <div style="padding-left: 100px;padding-right: 100px">

        <div style="padding-left: 30px;padding-right: 30px">

            <form class="layui-form layui-form-pane"  lay-filter="example" onsubmit="return false;" action="">
                <div style="padding-top: 10px;padding-bottom: 10px ">
                    <button class="layui-btn"  lay-submit lay-filter="formDemo">立即保存</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>

                <hr>

                <input type="hidden" name="id"    placeholder="请输入pid" autocomplete="off" class="layui-input" value="0">
                <input type="hidden" name="ismarker"     autocomplete="off" class="layui-input" value="true">

                <div class="layui-form-item">
                    <label class="layui-form-label">标题名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" required  lay-verify="required" placeholder="请输入标题名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标签名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="tag" required  lay-verify="required" placeholder="请输入标签名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <input type="hidden" name="channelId" required  lay-verify="required" placeholder="请输入标签名称" autocomplete="off" class="layui-input">
                <div class="layui-form-item">
                    <label class="layui-form-label">栏目名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="channelIdName" required  lay-verify="required" placeholder="请输入栏目名称" autocomplete="off" class="layui-input">
                    </div>
                </div>

            </form>
        </div>

        <div style="margin: 50px 0 50px 0;padding-left: 30px;padding-right: 30px">
            <div id="test-editormd">
                <textarea id="content-main" style="display:none;"></textarea>
            </div>
        </div>
    </div>

</div>
<div style="display: none" class="layuitree">
    <div id="treeView"></div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>

<script src="/js/common.js" charset="utf-8"></script>
<script src='/js/tools.js'></script>
<script src='/js/tree.js'></script>

<script>

    layui.use(['layer','form'], function () {
        var $ = layui.jquery,
            form = layui.form,
            layer = layui.layer;



        var testEditor;

        $(function() {
            testEditor = editormd("test-editormd", {
                width   : "100%",
                height  : 640,
                syncScrolling : "single",
                path    : "/editor/lib/"
            });
        });


        var url = decodeURI(window.location.href);
        var argsIndex = url.split("?obj=");
        var arg = argsIndex[1];


        let loginValited=api.valitLogin();
        if(loginValited.code===0){
            let info=loginValited.data;
            if(info.code!==200 && !info.isLogin){
                location.href="/console/login.html";
            }else {
                let username=loginValited.data.username;
                $("#username").html(username);
            }
        }

        init()
        function  init() {
            if(arg!==undefined && arg!==''){
                let obj=api.getContentExt(arg);
                if(obj.code===0){
                    //表单赋值
                    form.val('example',{
                        id:obj.data.id,
                        title:obj.data.title,
                        tag:obj.data.tag,
                        channelId:obj.data.channelId,
                        channelIdName:obj.data.channelName
                    });
                    console.log(obj.data.content);
                    $("#content-main").val(obj.data.content);
                }
            }
        }



        $('input[name="channelIdName"]').click(function() {
            var index = layer.open({
                title: '选择栏目',
                type: 1,
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                btn:['确定','取消'],
                area: ['32%', '70%'],
                content: $(".layuitree"),
                end:function(){

                }
            });
        });





        //监听提交
        form.on('submit(formDemo)', function (data) {
            let html=$("#content-main").val();
            let obj=data.field;
            obj.content=html;
            let res=api.saveContent(obj)
            layer.msg(res.msg)
            // let obj=api.saveChannel(data.field)
            // layer.msg(obj.msg)
            // if(obj.code===0){
            //     var iframeIndex = parent.layer.getFrameIndex(window.name);
            //     parent.layer.close(iframeIndex);
            // }else {
            //     return false;
            // }
        });


        let res={};
        let obj=api.getchanneltreelist(res);

        var treeView = tools.$('#treeView');
        var fileData = obj.data;


        treeView.innerHTML = treeHtml(fileData, -1);

        // 浜嬩欢
        var fileItem = tools.$('.treeNode');
        var root_icon = tools.$('.icon-control', fileItem[0])[0];

        root_icon.className = 'icon icon-control icon-minus';

        tools.each(fileItem, function (item) {
            filesHandle(item);
        });



        $(".treeNode").click(function() {
            let id=$(this).attr('data-file-id');
            let value=$(this).attr('data-file-value');
            console.log(id+" "+value)
            //表单赋值
            form.val('example',{
                channelId:id,
                channelIdName:value,
            });
        })

        function getLevelById(data,id) {
            return getParents(data,id).length;
        }

        function hasChilds(data,id){
            return getChildById(data,id).length !== 0;
        }

        function getChildById(arr,pid){
            var newArr = [];
            for( var i = 0; i < arr.length; i++ ){
                if( arr[i].pid == pid ){
                    newArr.push(arr[i]);
                }
            };

            return newArr;
        }

        function getParents(data,currentId){
            var arr = [];
            for( var i = 0; i < data.length; i++ ){
                if( data[i].id == currentId ){
                    arr.push(data[i]);
                    arr = arr.concat(getParents(data,data[i].pid))
                    break;
                }
            }
            return arr;
        }

        function treeHtml(fileData, fileId) {
            var _html = '';
            var children = getChildById(fileData, fileId);
            var hideChild = fileId > 0 ? 'none' : '';

            _html += '<ul class="'+hideChild+'">';

            children.forEach(function (item, index) {
                var level = getLevelById(fileData, item.id);
                var distance = (level - 1) * 20 + 'px';
                var hasChild = hasChilds(fileData, item.id);
                var className = hasChild ? '' : 'treeNode-empty';
                var treeRoot_cls = fileId === -1 ? 'treeNode-cur' : '';

                _html += `
        <li>
          <div class="treeNode ${className} ${treeRoot_cls}" style="padding-left: ${distance}" data-file-id="${item.id}" data-file-value="${item.title}">
            <i class="icon icon-control icon-add"></i>
            <i class="icon icon-file"></i>
            <span class="title">${item.title}</span>
          </div>
          ${treeHtml(fileData, item.id)}
        </li>`;
            });

            _html += '</ul>';

            return _html;
        };

        function filesHandle(item) {
            tools.addEvent(item, 'click', function () {
                var treeNode_cur = tools.$('.treeNode-cur')[0];
                var fileId = item.dataset.fileId;
                var curElem = document.querySelector('.treeNode[data-file-id="'+fileId+'"]');
                var hasChild = hasChilds(fileData, fileId);
                var icon_control = tools.$('.icon-control', item)[0];
                var openStatus = true;

                tools.removeClass(treeNode_cur, 'treeNode-cur');
                tools.addClass(curElem, 'treeNode-cur');

                if (hasChild) {
                    openStatus = tools.toggleClass(item.nextElementSibling, 'none');

                    if (openStatus) {
                        icon_control.className = 'icon icon-control icon-add';
                    } else {
                        icon_control.className = 'icon icon-control icon-minus';
                    }
                }
            });
        };

    });


</script>
</body>
</html>